﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Common.Entity;
using ESOL.Business.Prod;
using ESOL.Business.Inv;
using ESOL.Common;
using ESOL.Business.Mst;
using System.Text.RegularExpressions;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Manufacture
{
    public partial class frmMaintainPickingTask : BaseForm.frmBaseDialogyForm
    {

        #region vars
        private ProdPickingMaterialItemEntity mSelectedMaterialItem;
        public List<ProdPickingMaterialEntity> listSelectedPickingMaterial { set; get; }
        private DataRow drSelectedDataSource;

        #endregion

        #region ctors
        public frmMaintainPickingTask()
        {
            InitializeComponent();
        }
        #endregion

        #region functions
        private void Init()
        {
            //SelectedPickingMaterial = null;
            gvMain.DataSource = null;
            btnSave.Enabled = true;
        }

        private void BindCombobox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPickingType, "PICKT", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "PIKI", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit1, "PICKT", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit2, "UNIT", false);
        }

        private void SetField()
        {
            cmbStatus.SetSelectedValue("PIKI01");
        }

        private string GetCondition()
        {
            string sCondition = "";
            if (listSelectedPickingMaterial.Count > 0)
            {
                sCondition += "and PPMI.PICKING_MATERIAL_ID in (";
                foreach (ProdPickingMaterialEntity m in listSelectedPickingMaterial)
                {
                    sCondition += "'" + m.PickingMaterialId + "',";
                }
                sCondition = sCondition.Substring(0, sCondition.Length - 1) + ") ";
            }
            //if (SelectedPickingMaterial!=null)
            //{
            //    sCondition += "and PPMI.PICKING_MATERIAL_ID='" + SelectedPickingMaterial.PickingMaterialId+"' ";
            //}
            if (string.IsNullOrEmpty(cmbPickingType.SelectedValue.ToString()) == false)
            {
                sCondition += "and PPMI.PICKING_TYPE='" + cmbPickingType.SelectedValue.ToString() + "' ";
            }
            if (string.IsNullOrEmpty(cmbStatus.SelectedValue.ToString()) == false)
            {
                sCondition += "and PPMI.STATUS='" + cmbStatus.SelectedValue.ToString() + "' ";
            }
            return sCondition;
        }

        private void BindGrid()
        {
            string Condition = GetCondition();
            string sOrderBy = " ORDER BY MP2.PRODUCT_ID ";
            DataTable dt = ProdPickingMaterialItemBs.GetDtPickingMaterialItemByCondition(Condition, sOrderBy);
            dt.Columns.Add("INV_STORAGE_QTY",typeof(decimal));
            foreach (DataRow dr in dt.Rows)
            {
                if(dr["MATERIAL_ID"]==null)
                {
                    dr["INV_STORAGE_QTY"]=0.00;
                }

                dr["INV_STORAGE_QTY"] = InvStorageBs.GetActualStorageQty(dr["MATERIAL_ID"].ToString());
            }
            gvMain.DataSource = dt;
        }

        private bool CheckData()
        {
            DataTable dt = (DataTable)gvMain.DataSource;
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("放料数据为空，无法放料！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Convert.ToDecimal(dt.Rows[i]["ACTUAL_TOTAL_WEIGHT"].ToString()) == 0)
                {
                    MessageBox.Show("放料重量不可为：0", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    gridView1.SelectRow(i);
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 更新放料实际重量->出库->报工
        /// </summary>
        /// <returns></returns>
        private bool Picking()
        {
            DataTable dt = (DataTable)gvMain.DataSource;

            List<ProdPickingMaterialEntity> listPickingMaterialNew = new List<ProdPickingMaterialEntity>();
            List<ProdPickingMaterialItemEntity> listPickingMaterialItemNew = new List<ProdPickingMaterialItemEntity>();
            List<InvDispatchOrderEntity> listDispatchOrderNew = new List<InvDispatchOrderEntity>();
            Dictionary<string, List<InvDispatchItemEntity>> dict = new Dictionary<string, List<InvDispatchItemEntity>>();
            IEnumerable<IGrouping<string, DataRow>> result = dt.Rows.Cast<DataRow>().GroupBy<DataRow, string>(dr => dr["PICKING_MATERIAL_ID"].ToString());//按A分组
            foreach (IGrouping<string, DataRow> ig in result)
            {
                ProdPickingMaterialEntity mPickingMaterialNew = ProdPickingMaterialBs.GetProdPickingMaterialByID(ig.Key);
                //放料单状态
                DataTable dtAllPickingOrderItem = ProdPickingMaterialItemBs.GetDtPickingMaterialItemByPickingID(ig.Key);
                bool bIsPickingCompleted = true;
                foreach (DataRow dr in dtAllPickingOrderItem.Rows)
                {
                    bool bFlag = false;
                    foreach (DataRow dr1 in dt.Rows)
                    {
                        if (dr["PICKING_MATERIAL_ITEM_ID"].ToString().Equals(dr1["PICKING_MATERIAL_ITEM_ID"].ToString()))
                        {
                            bFlag = true;
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if (bFlag == true)
                        continue;
                    else
                    {
                        if (dr["STATUS"].ToString().Equals("PIKI01"))
                        {
                            bIsPickingCompleted = false;
                            break;
                        }
                    }
                }
                if (bIsPickingCompleted)
                {
                    mPickingMaterialNew.Status = "PIK02";
                    listPickingMaterialNew.Add(mPickingMaterialNew);
                }
               // DataTable dtStorage = InvStorageBs.GetInvStroageByID();
                InvDispatchOrderEntity mDispatchOrder = new InvDispatchOrderEntity();
                mDispatchOrder.DispatchOrderId = Guid.NewGuid().ToString();
                mDispatchOrder.OrderType = "IDT02";
                mDispatchOrder.OrderDate = DateTime.Now;
                mDispatchOrder.OrderPerson = CommonParameter.CurrentUser.PersonId;
                mDispatchOrder.RelatedOrder = mPickingMaterialNew.PickingMaterialId;
                mDispatchOrder.CreatedDate = DateTime.Now;
                mDispatchOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
                mDispatchOrder.LastModifiedDate = DateTime.Now;
                mDispatchOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                mDispatchOrder.Status = "IDO03";
                mDispatchOrder.Remark = "放料单：" + mPickingMaterialNew.PickingCode + " 材料出库时自动产生";
                listDispatchOrderNew.Add(mDispatchOrder);

                List<InvDispatchItemEntity> listDispatchItemNew = new List<InvDispatchItemEntity>();
                foreach (var dr in ig)
                {
                    ProdPickingMaterialItemEntity mPickingMaterialItemNew = new ProdPickingMaterialItemEntity(dr);
                    mPickingMaterialItemNew.Status = "PIKI02";
                    listPickingMaterialItemNew.Add(mPickingMaterialItemNew);

                    //一个库位物料库存量取完后取第二个库位
                    decimal actualTotalWeight = Convert.ToDecimal(dr["ACTUAL_TOTAL_WEIGHT"].ToString());
                    DataTable dtInvstorage = InvStorageBs.GetInvStroageByID(dr["MATERIAL_ID"].ToString());
                    decimal dValue = actualTotalWeight;
                    foreach(DataRow drStorage in dtInvstorage.Rows )
                    {
                        dValue = dValue - Convert.ToDecimal(drStorage["CURRENT_QTY"].ToString());
                        if (dValue <= 0)
                        {
                            InvDispatchItemEntity mDispatchItemNew = new InvDispatchItemEntity();
                            mDispatchItemNew.DispatchItemId = Guid.NewGuid().ToString();
                            mDispatchItemNew.DispatchOrderId = mDispatchOrder.DispatchOrderId;
                            mDispatchItemNew.ProductId = dr["MATERIAL_ID"].ToString();
                            mDispatchItemNew.LocationId = drStorage["LOCATION_ID"].ToString();
                            mDispatchItemNew.Qty = dValue + Convert.ToDecimal(drStorage["CURRENT_QTY"].ToString());
                            mDispatchItemNew.Remark = "放料时系统自动出库";
                            listDispatchItemNew.Add(mDispatchItemNew);
                            break;
                        }
                        else
                        {
                            InvDispatchItemEntity mDispatchItemNew = new InvDispatchItemEntity();
                            mDispatchItemNew.DispatchItemId = Guid.NewGuid().ToString();
                            mDispatchItemNew.DispatchOrderId = mDispatchOrder.DispatchOrderId;
                            mDispatchItemNew.ProductId = dr["MATERIAL_ID"].ToString();
                            mDispatchItemNew.LocationId = drStorage["LOCATION_ID"].ToString();
                            mDispatchItemNew.Qty = Convert.ToDecimal(drStorage["CURRENT_QTY"].ToString());
                            mDispatchItemNew.Remark = "放料时系统自动出库";
                            listDispatchItemNew.Add(mDispatchItemNew);
                        }

                    }

                    
                    

                }
                dict.Add(mDispatchOrder.DispatchOrderId, listDispatchItemNew);
            }
            string sErrMsg = "";
            if (ProdPickingMaterialItemBs.Picking(listPickingMaterialNew, listPickingMaterialItemNew, listDispatchOrderNew, dict, out sErrMsg))
            {
                return true;
            }
            else
            {
                MessageBox.Show(sErrMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region events
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindCombobox();
            SetField();
            if (listSelectedPickingMaterial != null)
            {
                BindGrid();
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            BindGrid();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckData() == false)
                return;
            if (Picking())
            {
                MessageBox.Show("放料完成！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Init();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            string sActualTotalWeight = this.gridView1.GetRowCellValue(e.RowHandle, "ACTUAL_TOTAL_WEIGHT").ToString().Trim();
            if (string.IsNullOrEmpty(sActualTotalWeight) == true)
            {
                e.Valid = false;
                this.gridView1.SetColumnError(this.gridView1.Columns["gridColumn6"], "请填写放料重量!", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
            }
            else if (Convert.ToDecimal(sActualTotalWeight) == 0)
            {
                e.Valid = false;
                this.gridView1.SetColumnError(this.gridView1.Columns["gridColumn6"], "放料重量不可为：0!", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
            }
        }

        private void gridView1_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            if (this.gridView1.FocusedColumn.FieldName == "ACTUAL_TOTAL_WEIGHT")
            {
                if (string.IsNullOrEmpty(e.Value.ToString()) == false)
                {
                    if (Common.CommonFunctions.IsDecimal(e.Value.ToString()) == false)
                    {
                        e.Valid = false;
                        e.ErrorText = "放料重量必须为数字";
                    }
                    else if (Convert.ToDecimal(e.Value.ToString()) == 0)
                    {
                        e.Valid = false;
                        e.ErrorText = "放料重量不可为：0";
                    }
                }
            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            frm.sCondition = " and C.PRODUCT_TYPE_CODE='d' ";
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                drSelectedDataSource["MATERIAL_ID"] = frm.SelectedProduct.ProductId;
                MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(frm.SelectedProduct.ProductId);
                if (mProduct != null)
                {
                    drSelectedDataSource["MATERIAL_PRODUCT_NAME"] = mProduct.ProductName;
                }
                drSelectedDataSource["ACTUAL_TOTAL_WEIGHT"] = 0.00;
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
                return;
            DataTable dt = (DataTable)gvMain.DataSource;
            if (dt.Rows.Count == 0)
                return;
            drSelectedDataSource = gridView1.GetDataRow(e.FocusedRowHandle);
            mSelectedMaterialItem = new ProdPickingMaterialItemEntity(drSelectedDataSource);

        }

        #endregion
    }
}
